﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using KLadderProposal.Interfaces;
using KLadderProposal.Interfaces.BasicStructures;

namespace KLadderProposal.Documents
{
    public class GraphDocumentForOverlapingClusters : IGraphDocument
    {
        public void Load(Interfaces.IGraph graph, string filePath)
        {
            string fileContent = File.ReadAllText(filePath);

            string[] pairs = fileContent.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            for (int i = 1; i < pairs.Length; i++)
            {
                string[] labels = pairs[i].Split('\t');
                if (labels.Length > 1)
                    graph.AddUndirectedEdge(labels[0], labels[1].Replace("\r", string.Empty));
            }

            stopwatch.Stop();
        }

        public void Save(Interfaces.IGraph graph, string filePath)
        {
            StringBuilder pajekFileContent = new StringBuilder("*Network KLadder\n\r");

            pajekFileContent.AppendFormat("*Vertices {0}\n\r", graph.Count);
            foreach (GraphNode graphNode in graph.Nodes)
                pajekFileContent.AppendFormat("{0} \"{1}\" 0.0 0.0\n\r", graphNode.SequenceNumber, graphNode.Label);

            pajekFileContent.AppendFormat("*Edges {0}\n\r", graph.Count);
            foreach (GraphNode graphNode in graph.Nodes)
                foreach (GraphNode neighbor in graphNode.Neighbors.Values)
                    pajekFileContent.AppendFormat("{0} {1}\n\r", graphNode.SequenceNumber, neighbor.SequenceNumber);

            pajekFileContent.Append("*Partition KLadder\n\r");
            pajekFileContent.AppendFormat("*Vertices {0}\n\r", graph.Count);
            foreach (GraphNode graphNode in graph.Nodes)
            {
                foreach (int clusterNumber in graphNode.ClusterNumbers)
                    pajekFileContent.AppendFormat("{0},", clusterNumber);

                pajekFileContent.Remove(pajekFileContent.Length - 1, 1);
                pajekFileContent.Append("\n\r");
            }

            File.WriteAllText(filePath, pajekFileContent.ToString());
        }
    }
}
